import axios from "axios";
import Vue from 'vue'

let baseUrl = "";


function getBaseConfig () {
  let token = mySessionStorage.getItem('token')
  return {
    baseURL: baseUrl,
    timeout: 60000,
    headers: { 'access_token': token }
  }
}

axios.interceptors.request.use(function (config) {
  // console.log(config.url, config.params, config.data)
  let params = config.params || {}
  let data = config.data || {}
  config.url = config.url.replace(/{(\w+)}/g, (a, b) => params[b] || data[b])
  return config;
}, function (error) {
  return Promise.reject(error);
})

// 添加响应拦截器
axios.interceptors.response.use(function (response) {
  // 对响应数据做点什么
  let data = response.data;
  if (data.hasOwnProperty("code")) {
    if (`${data.code}` !== "0") {
      return Promise.reject(new Error(data.message));
    } else {
      return data.data;
    }
  }
  if (data instanceof Blob) {
    return response
  }
  return data;
}, async function (error) {
  // 对响应错误做点什么
  let response = error.response
  if (response && (response.data instanceof Blob)) {
    if (response.data.type === "application/json") {
      return new Promise((resolve, reject) => {
        let reader = new FileReader();
        reader.onload = e => {
          let res = JSON.parse(reader.result)
          reject(new Error(res.message))
        }
        reader.readAsText(response.data);
      })
    }
    return Promise.reject(new Error("请求出错"));
  } else if (response) {
    return Promise.reject(new Error(response.data.message));
  }
  return Promise.reject(error);
});

let loading = null
let loadingCount = 0;
export default {
  setBaseUrl (_baseUrl) {
    baseUrl = _baseUrl
    console.log("当前baseUrl", baseUrl)
  },
  setToken (_token) {
    mySessionStorage.setItem("token", _token)
  },
  async post (url, args) {
    let [arg, options = {}, loadingConfig = { loading: true, loadingText: '数据加载中，请稍后' }] = args
    if (loadingConfig.loading) {
      if (!loading) {
        loading = Vue.prototype.$loading({ lock: true, text: loadingConfig.loadingText });
      }
      loading.text = loadingConfig.loadingText
      loadingCount++
    }
    try {
      return await axios.request({
        url,
        method: "POST",
        ...getBaseConfig(),
        data: arg,
        ...options
      })
    } finally {
      if (loadingConfig.loading) {
        loadingCount--
        if (!loadingCount) {
          loading.close()
          loading = null
        }
      }
    }
  },
  async get (url, args) {
    let [arg, options = {}, loadingConfig = { loading: true, loadingText: '数据加载中，请稍后' }] = args
    if (loadingConfig.loading) {
      if (!loading) {
        loading = Vue.prototype.$loading({ lock: true, text: loadingConfig.loadingText });
      }
      loading.text = loadingConfig.loadingText
      loadingCount++
    }
    try {
      return await axios.request({
        url,
        method: "GET",
        ...getBaseConfig(),
        params: arg,
        ...options
      })
    } finally {
      if (loadingConfig.loading) {
        loadingCount--
        if (!loadingCount) {
          loading.close()
          loading = null
        }
      }
    }
  },
}
